<?php


namespace App\Controller;


use SidToken\Model\QueueModel;
use SidToken\Model\SidMinerFakebuyModel;
use SidToken\Model\SidMinerModel;
use SidToken\Model\SidMinerProductionLogModel;
use SidToken\Model\SidTransferLogModel;
use SidToken\Model\SidUserMinerModel;
use SidToken\Utils\MemberWalletUtil;
use SidToken\Utils\TrxRpc;

class PoolController extends AppBaseController
{
    public function index()
    {
        $uid = $this->getUid();
        $MinerProductionModel = new SidMinerProductionLogModel();
        $fakeMinerModel = new SidMinerFakebuyModel();
        $poolTotalProduction = floatval($MinerProductionModel->getPoolTotalPruduction());
        $fakeMinerAmount = $fakeMinerModel->calculateTotalFakeMiner();

        $return = [
            'yesterday_out' => $poolTotalProduction + $fakeMinerAmount,
            'pool_sid' => 180000000 - $poolTotalProduction - $fakeMinerAmount,
            'user_yesterday_out' => floatval($MinerProductionModel->getUserYesterdayProduction($uid)),
            'user_total_out' => floatval($MinerProductionModel->getUserTotalPruduction($uid))
        ];

        $this->jsuccess($return);
    }

    public function listBuy()
    {
        $Miner = new SidMinerModel();
        $lists = $Miner->where(['status' => $Miner::STATUS_ON])->order("sort DESC,id DESC")->select();
        foreach ($lists as &$val) {
            $val['price'] = floatval($val['price']);
            $val['price_sid'] = floatval($val['price_sid']);
            $val['day_amount'] = floatval($val['day_amount']);
        }
        $this->jsuccess($lists);
    }

    public function minerDetail($id)
    {
        $Miner = new SidMinerModel();
        $data = $Miner->find($id);
        if ($data['status'] != $Miner::STATUS_ON) {
            $data = [];
        }
        $this->jsuccess($data);
    }

    /**
     * 准备购买矿机
     */
    public function preBuyMiner()
    {
        $minerId = I("id", 0, 'intval');
        $uid = $this->getUid();
        if (!$minerId) {
            $this->jerror("param id is empty");
        }
        $UserMinerModel = new SidUserMinerModel();
        $userCanBuyAmount = $UserMinerModel->userCanBuyAmount($uid, $minerId);
        //$address = get_address($uid);

        //$TrxRpc = new TrxRpc();
        $return = [
            'min' => $userCanBuyAmount > 0 ? 1 : 0,
            'max' => $userCanBuyAmount,
            'balance' => get_user_usdt_balance($uid),
            'sid_balance' => get_user_sid_balance($uid)
        ];
        $this->jsuccess($return);
    }

    public function buyMiner()
    {
        $MinerModel = new SidMinerModel();
        $UserMinerModel = new SidUserMinerModel();

        $minerId = I("miner_id", '', 'intval');
        $buyAmount = I("buy_amount", 1, 'intval');
        $uid = $this->getUid();
        $this->checkPassword($uid);

        if ($buyAmount < 1) {
            $this->jerror("购买数量只能为大于0的整数");
        }

        $userCanBuyAmount = $UserMinerModel->userCanBuyAmount($uid, $minerId);
        if ($userCanBuyAmount - $buyAmount < 0) {
            $this->jerror("最多可购买{$userCanBuyAmount}台");
        }

        $uid = $this->getUid();

        $miner = $MinerModel->get($minerId);
        $startTime = $miner['start_time'];
        if (time() > $startTime) {
            $minerStartTime = strtotime(date('Ymd')) + 86400;
        } else {
            $minerStartTime = $startTime;
        }
        $minerEndTime = $minerStartTime + 86400 * $miner['release_day'];

        $price = $miner['price'];
        $priceSid = $miner['price_sid'];

        $totalUsdt = $price * $buyAmount;
        $totalSid = $priceSid * $buyAmount;

        $userBalance = get_user_usdt_balance($uid);


        if ($totalUsdt > $userBalance) {
            $this->jerror("USDT 不足");
        }
        if ($totalSid > 0) {
            $userSidBalance = get_user_sid_balance($uid);
            if ($totalSid > $userSidBalance) {
                $this->jerror("SID 不足");
            }
        }


        $WalletUtil = new MemberWalletUtil();
        $result = $WalletUtil->changeUsdt($uid, 'dec', 'inner transfer', 'inner transfer', time() . mt_rand(1000, 9999), $totalUsdt, "购买" . $miner['name']);
        if ($result && $totalSid > 0)
            $result = $WalletUtil->changeSid($uid, 'dec', 'inner transfer', 'inner transfer', time() . mt_rand(1000, 9999), $totalSid, "购买" . $miner['name']);

        if ($result) {
            $index = 0;
            $lastId = 0;
            $MinerModel->updateSellAmount($minerId, $buyAmount);
            while ($index < $buyAmount) {
                $data = [
                    'uid' => $uid,
                    'order_sn' => time() . mt_rand(1000, 9999),
                    'name' => $miner['name'],
                    'total_get_amount' => $miner['day_amount'] * $miner['release_day'],
                    'start_time' => $minerStartTime,
                    'create_time' => time(),
                    'end_time' => $minerEndTime,
                    'day_amount' => $miner['day_amount'],
                    'miner_id' => $minerId,
                    'status' => $UserMinerModel::STATUS_ON,
                    'type' => $UserMinerModel::TYPE_BUY
                ];
                $lastId = $data['id'] = $UserMinerModel->add($data);
                $index++;
            }
            $return = [
                'total_usdt' => $totalUsdt,
                'total_sid' => $totalSid,
                'buy_amount' => $buyAmount,
                'name' => $miner['name'],
                'id' => $lastId
            ];

            $postParams = [
                'miner_id' => $minerId,
                'miner_name' => $miner['name'],
                'miner_day_amount' => $miner['day_amount'],
                'miner_release_day' => $miner['release_day'],
                'limit_amount' => $miner['limit_amount'],
                'uid' => $uid
            ];
            $QueueModel = new QueueModel();
            $rewardBuyUrl = getApiUrl() . "/App/Reward/rewardBuyMiner";
            //推荐奖励
            $QueueModel->addQueue(M(), [], $rewardBuyUrl, $postParams);

            $this->jsuccess($return);
        } else {
            $this->jerror("余额不足，操作失败");
        }
    }

    public function userMinerLists()
    {
        $uid = $this->getUid();
        $UserMinerModel = new SidUserMinerModel();
        $ProductionLogModel = new SidMinerProductionLogModel();
        $lists = $UserMinerModel->where(['uid' => $uid])->order("create_time ASC")->select();
        foreach ($lists as &$val) {
            $total = $ProductionLogModel->getTotalPruduction($uid, $val['id']);
            $val['total_production'] = $total;
            $val['total_get_amount'] = floatval($val['total_get_amount']);
            $val['day_amount'] = floatval($val['day_amount']);
            $val['total_production'] = floatval($val['total_production']);
            $val['status_str'] = $UserMinerModel->statusString($val['status'], $val['start_time']);
        }
        $this->jsuccess($lists);
    }

    /**
     * 用户收益记录
     */
    public function userMinerProductionLog()
    {
        $page = I("page", 1, 'intval');
        $uid = $this->getUid();
        $ProductionLogModel = new SidMinerProductionLogModel();

        $lists = $ProductionLogModel->where(['uid' => $uid])->order("create_time DESC")->page($page, 20)->select();
        foreach ($lists as &$val) {
            $val['create_time'] = date("Y-m-d", $val['create_time']);
            $val['amount'] = '+' . floatval($val['amount']);
        }
        $this->jsuccess($lists);
    }

    public function userProductionAnalysis()
    {
        $MinerProductionLogModel = new SidMinerProductionLogModel();
        $uid = $this->getUid();
        $totalProduction = $MinerProductionLogModel->getUserTotalPruduction($uid);
        $yesterdayProduction = $MinerProductionLogModel->getUserYesterdayProduction($uid);
        $return = [
            'total_production' => floatval($totalProduction),
            'yesterday_production' => floatval($yesterdayProduction)
        ];
        $this->jsuccess($return);
    }

    public function userMinerDetail($id)
    {
        $uid = $this->getUid();
        //$MinerModel = new SidMinerModel();
        $UserMinerModel = new SidUserMinerModel();
        $MinerProductionLogModel = new SidMinerProductionLogModel();
        $data = $UserMinerModel->find($id);
        if ($data['uid'] != $this->getUid()) {
            $this->jerror('数据不存在');
        }
        $data['total_get_amount'] = floatval($data['total_get_amount']);
        $data['day_amount'] = floatval($data['day_amount']);
        $return = $data;

        $return['start_time'] = date("Y-m-d", $data['start_time']);
        if ($data['start_time'] > time()) {//矿机还未开始运行
            $return['running_day'] = 0;
            $return['left_day'] = ($data['end_time'] - $data['start_time']) / 86400;
        } else {//矿机已开始
            $return['running_day'] = (strtotime(date('Ymd')) - $data['start_time']) / 86400;
            $return['running_day']++;
            if ($data['end_time'] < time()) {
                $return['running_day'] = ($data['end_time'] - $data['start_time']) / 86400;
            }
            $return['left_day'] = ($data['end_time'] - strtotime(date('Ymd'))) / 86400;
            $return['left_day']--;
            if ($return['left_day'] < 0) {
                $return['left_day'] = 0;
            }
        }

        //if($return['left_day']>$return[''])
        $return['end_time'] = date("Y-m-d H:i:s", $data['end_time']);
        $return['power'] = $return['day_amount'] * 10;
        $totalProduction = $MinerProductionLogModel->getTotalPruduction($uid, $id);
        $yesterdayProduction = $MinerProductionLogModel->getYesterdayProduction($uid, $id);
        $return['total_production'] = floatval($totalProduction);
        $return['yesterday_production'] = floatval($yesterdayProduction);
        $this->jsuccess($return);

    }


}